package com.library.management.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.library.management.common.Result;
import com.library.management.domain.user.User;
import com.library.management.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.List;

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 分页获取用户列表
     */
    @GetMapping("/page")
    public Result<Page<User>> getUserPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String realName) {
        try {
            Page<User> page = new Page<>(current, size);
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            
            if (username != null && !username.trim().isEmpty()) {
                queryWrapper.like(User::getUsername, username);
            }
            if (realName != null && !realName.trim().isEmpty()) {
                queryWrapper.like(User::getRealName, realName);
            }
            
            queryWrapper.orderByDesc(User::getCreateTime);
            Page<User> userPage = userService.page(page, queryWrapper);
            return Result.success(userPage);
        } catch (Exception e) {
            return Result.error("获取用户列表失败");
        }
    }

    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    public Result<List<User>> getUserList() {
        try {
            List<User> userList = userService.getUserList();
            return Result.success(userList);
        } catch (Exception e) {
            return Result.error("获取用户列表失败");
        }
    }

    /**
     * 新增用户
     */
    @PostMapping("/add")
    public Result<Void> addUser(@RequestBody User user) {
        try {
            // 检查用户名是否已存在
            if (userService.getByUsername(user.getUsername()) != null) {
                return Result.error("用户名已存在");
            }

            // 加密密码
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            
            // 设置默认值
            if (user.getStatus() == null) {
                user.setStatus(1); // 默认启用
            }
            if (user.getUserType() == null) {
                user.setUserType(0); // 默认普通用户
            }

            userService.save(user);
            return Result.success();
        } catch (Exception e) {
            return Result.error("新增用户失败");
        }
    }

    /**
     * 更新用户
     */
    @PutMapping("/update")
    public Result<Void> updateUser(@RequestBody User user) {
        try {
            // 检查用户是否存在
            User existingUser = userService.getById(user.getId());
            if (existingUser == null) {
                return Result.error("用户不存在");
            }

            // 如果修改了用户名，检查新用户名是否已存在
            if (!existingUser.getUsername().equals(user.getUsername())) {
                if (userService.getByUsername(user.getUsername()) != null) {
                    return Result.error("用户名已存在");
                }
            }

            // 如果密码不为空，则加密密码
            if (user.getPassword() != null && !user.getPassword().trim().isEmpty()) {
                user.setPassword(passwordEncoder.encode(user.getPassword()));
            } else {
                // 如果密码为空，使用原密码
                user.setPassword(existingUser.getPassword());
            }

            userService.updateById(user);
            return Result.success();
        } catch (Exception e) {
            return Result.error("更新用户失败");
        }
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable Long id, Principal principal) {
        try {
            // 获取当前登录用户名
            String currentUsername = principal.getName();
            User currentUser = userService.getByUsername(currentUsername);

            // 检查是否在删除自己
            if (currentUser != null && currentUser.getId().equals(id)) {
                return Result.error("不能删除当前登录用户");
            }
            
            User user = userService.getById(id);
            if (user == null) {
                return Result.error("用户不存在");
            }

            userService.removeById(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error("删除用户失败");
        }
    }
} 